package cn.yunyichina.provider.bone.listener;

import cn.yunyichina.provider.bone.service.impl.BoneMsgServiceImpl;
import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.MessageService;
import cn.yunyichina.provider.framework.dubbo.service.OrderService;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.bone.OrderBoneExtendVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.listener.MessageListener;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/2/10.
 */
public class BoneDepositAlipayPayMessageListener implements MessageListener<Integer, String> {
    private Logger logger = LoggerFactory.getLogger(BoneDepositAlipayPayMessageListener.class);

    @Override
    public void onMessage(ConsumerRecord<Integer, String> integerStringConsumerRecord) {
		logger.info("BoneDepositAlipayPayMessageListener onMessage start.");
		String jsonString = integerStringConsumerRecord.value();
		logger.info("BoneDepositAlipayPayMessageListener.onMessage.jsonString骨科问诊/押金单回调, 入参 -> {}", jsonString);
        try {
			JSONObject jsonObject = JSON.parseObject(jsonString);
            String orderNo = (String)jsonObject.get("out_trade_no");
            String appId = (String)jsonObject.get("app_id");
            String payMode = (String)jsonObject.get("pay_mode");
            String paymentDealId = (String) jsonObject.get("trade_no");
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("order_no", orderNo);
            logger.info("BoneDepositAlipayPayMessageListener骨科问诊/押金单回调, 订单号" + orderNo + ", 调base模块, 查询订单信息入参request=" + JSONObject.toJSONString(dataMap));
            Response ordResponse = BaseService.callUnderlineFromInternal("", "yyt.base.order.by.order.no.out.get",
                    JsonUtils.toJsonString(dataMap));
            logger.info("BoneDepositAlipayPayMessageListener骨科问诊/押金单回调, 订单号" + orderNo + ", 调base模块, 查询订单信息返回response=" + JSONObject.toJSONString(ordResponse));
            if ("0".equals(ordResponse.getResultCode())) {
                OrderExtVo vo = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);
                vo.setPayTime(DateUtils.dateToString(new Date()));
                vo.setUpdateTime(DateUtils.dateToString(new Date()));
                // 91-已缴问诊费
                vo.setOrderStatus((short) 91);
                // 已支付
                vo.setPayStatusPayed();
                vo.setPayAppId(appId);
                vo.setPayMode(Short.parseShort(payMode));
                // 支付流水
                vo.setPaymentDealId(paymentDealId);
                logger.info("BoneDepositAlipayPayMessageListener骨科问诊/押金单回调, 订单号" + orderNo + ", 调base模块, 更新订单信息入参request=" + JSONObject.toJSONString(vo));
                BaseService.callUnderlineFromInternal("", "yyt.base.order.update", JsonUtils.toJsonString(vo));
                
                // 发送推送消息
                sendMessage(vo);
            } else {
                logger.info("BoneDepositAlipayPayMessageListener骨科问诊/押金单回调, 订单号" + orderNo + ", 调base模块, 查不到该订单.");
            }
        } catch (Exception e) {
            logger.error("BoneDepositAlipayPayMessageListener骨科问诊/押金单回调报错", e);
        }
        logger.info("BoneDepositAlipayPayMessageListener骨科问诊/押金单回调处理结束.");
    }
    
    // 发送微信/短信通知
    private void sendMessage(OrderExtVo vo) {
    	logger.info("BoneDepositAlipayPayMessageListener骨科问诊/押金单回调, 发送推送消息");
    	try {
	    	final BoneMsgServiceImpl boneMsgService = SpringContextHandler.getBean("boneMsgServiceImpl");
	    	final String orderNo = vo.getOrderNo();
	    	final short orderType = vo.getOrderType();
	    	final String patientName = vo.getUserName();

			final JSONObject request=new JSONObject();
			request.put("order_no",vo.getOrderNo());
			request.put("app_id",vo.getPayAppId());
			request.put("open_id",vo.getOpenId());
	    	
	    	// 患者支付预付费／问诊费完成
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					// 发送微信给患者
					logger.info("发送支付宝通知给患者");
					boneMsgService.sendBoneMsgSuccessOrder(request.toJSONString());
					
					// 查询订单的拓展信息，是否有主治医生
					logger.info("BoneDepositAlipayPayMessageListener骨科问诊/押金查询订单的拓展信息，是否有主治医生入参orderNo："+orderNo);
					Response orderRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.order.get", "{\"order_no\":\"" + orderNo + "\"}");
					logger.info("BoneDepositAlipayPayMessageListener骨科问诊/押金查询订单的拓展信息，是否有主治医生出参："+JSON.toJSONString(orderRespone));
					OrderBoneExtendVo orderExtend = JsonUtils.parseObject(orderRespone.getResult(), OrderBoneExtendVo.class);
					String professorDoctorId = orderExtend.getProfessorDoctorId();
					if (StringUtils.isNotBlank(professorDoctorId)) {
						// 有主治医生
						// 查询主治医生的信息
						logger.info("BoneDepositAlipayPayMessageListener查询主治医生的信息入参professorDoctorId："+professorDoctorId);
						Response professorResponse = BaseService.callHumpFromInternal(
								"yyt.base.orguser.info.get", "{\"user_id\":\""
										+ professorDoctorId + "\"}");
						logger.info("BoneDepositAlipayPayMessageListener查询主治医生的信息出参："+professorResponse);
						String professorResult = professorResponse.getResult();
						if (StringUtils.isBlank(professorResult)) {
							logger.error("发送短信通知给医生异常，未查询到医生信息 userId: " + professorDoctorId);
							return;
						}
						
						logger.info("医生信息: " + professorResult);
						JSONObject resultMap = JSON.parseObject(professorResult);
						String mobile = resultMap.getString("mobile");
						String doctorName = resultMap.getString("userName");
						
						Map<String, Object> data = new HashMap<>();
						data.put("user_type", "5");
						data.put("to_user", mobile);
						data.put("msg_type", 94);
						Map<String, String> msgContent = new HashMap<>();
						msgContent.put("user_name", patientName);
						msgContent.put("order_type_name", orderType == 91 ? "问诊单" : "手术单");
						msgContent.put("doctor_name", doctorName);
						data.put("msg_content", msgContent);
						
						String dataJson = JSON.toJSONString(data);
						// 发送短信给医生
						logger.info("发送短信给医生，参数: " + dataJson);
						MessageService.callUnderlineFromInternal("yyt.message.msg.sms.send", dataJson);
					}
				}
			}).start();
    	} catch (Exception e) {
    		logger.error("骨科问诊/押金单回调, 发送推送消息异常", e);
    	}
    }
}
